﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Web.Mvc;
using System.ComponentModel;
using EIIS.Infrastructure.Service.System;
using EIIS.Infrastructure.Model.System;
using EIIS.Presentation.Controllers.CommonSupport;
using EIIS.Presentation.Controllers.ViewModel;
using EIIS.Common.Jsons;
using EIIS.FrameWork.Attributes;

namespace EIIS.Presentation.Controllers.System
{
    [Description("数据字典分类管理")]
    public class DicCategoryController : BaseController
    {
        public IDicCategoryManager DicCategoryManager { get; set; }
        public IDictionaryManager DictionaryManager { get; set; }

        [Description("数据字典分类管理页面")]
        [ViewPage]
        public ActionResult Index()
        {           
            AddDicCategoryRoot();
            return View();
        }

        public ActionResult LoadAll()
        {
            IList<DicCategory> list = DicCategoryManager.LoadAll();
            List<DicCategoryGrid> gridList = ConvertToGrid(list);
            return this.JsonFormat(new GridData { total = gridList.Count, rows = gridList });
        }

        [Description("新增数据字典分类")]
        [Function(ButtonID = "btnAdd")]
        public ActionResult Add(string id)
        {
            DicCategory parent = this.DicCategoryManager.Get(id);
            DicCategory entity = new DicCategory
            {
                Name = string.Empty,
                ParentId = parent.Id,
                ParentName = parent.Name,
                Description = string.Empty,
                Level = parent.Level + 1
            };
            this.ViewData["entity"] = entity;
            return View();
        }

        [Description("修改数据字典分类")]
        [Function(ButtonID = "btnUpdate")]
        public ActionResult Edit(string id)
        {
            DicCategory entity = this.DicCategoryManager.Get(id);
            this.ViewData["entity"] = entity;
            return View();
        }

        [Description("保存数据字典分类")]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Save(DicCategory entity)
        {
            IList<DicCategory> list;
            string strHql = "from DicCategory d where d.TreeCode='" + entity.TreeCode + "'";
            if (string.IsNullOrEmpty(entity.Id))//新增
            {
                list = DicCategoryManager.Find(strHql);
                if (list.Count() > 0)
                {
                    return Json(new { IsSuccess = false, Message = "新增失败，已存在该分类编码的记录" });
                }
                entity.Id = Guid.NewGuid().ToString();
                entity.ParentId = entity.ParentId;
                this.DicCategoryManager.Save(entity);
            }
            else//修改
            {
                strHql = "from DicCategory d where d.TreeCode='" + entity.TreeCode + "' and d.Id<>'" + entity.Id + "'";
                list = DicCategoryManager.Find(strHql);
                if (list.Count() > 0)
                {
                    return Json(new { IsSuccess = false, Message = "修改失败，已存在该分类编码的记录" }, "application/json", JsonRequestBehavior.AllowGet);
                }

                var model = this.DicCategoryManager.Get(entity.Id);
                model.Name = entity.Name;
                model.Description = entity.Description;
                model.TreeCode = entity.TreeCode;
                model.Index = entity.Index;
                this.DicCategoryManager.Update(model);
            }

            return Json(new { IsSuccess = true, Message = "保存成功" }, "text/html", JsonRequestBehavior.AllowGet);
        }

        [Description("删除数据字典分类")]
        [Function(ButtonID = "btnDelete")]
        public ActionResult Delete(IList<string> idList)
        {
            StringBuilder sb = new StringBuilder();
            foreach (string strId in idList)
            {
                sb.AppendFormat(",'{0}'", strId);
            }
            sb.Remove(0, 1);

            string strSql = string.Format("select count(1) as counts from Sys_DicCategory where PARENT_ID in({0}) union all select count(1) as counts from Sys_Dictionary where DICCATEGORY_ID in ({0})", sb.ToString());
            IList list = DictionaryManager.ExecuteSelectSQL(strSql);
            if (list.Count == 2)
            {
                if (Convert.ToInt32(list[0]) > 0)
                {
                    return Json(new { IsSuccess = false, Message = "删除失败，您所删除的数据中有子信息，请重新选择" });
                }
                if (Convert.ToInt32(list[1]) > 0)
                {
                    return Json(new { IsSuccess = false, Message = "删除失败，您所删除的数据中有条目信息，请重新选择" });
                }
            }

            this.DicCategoryManager.Delete(idList.Cast<object>().ToList());
            return Json(new { IsSuccess = true, Message = "删除成功" });
        }


        #region 私有方法

        private DicCategoryGrid ConvertToGrid(DicCategory dicCategory)
        {
            DicCategoryGrid grid = new DicCategoryGrid();
            grid.id = dicCategory.Id;
            grid.name = dicCategory.Name;
            grid.code = dicCategory.TreeCode;
            grid._parentId = dicCategory.ParentId;
            grid.description = dicCategory.Description;
            grid.index = dicCategory.Index;

            return grid;
        }

        private List<DicCategoryGrid> ConvertToGrid(IList<DicCategory> iList)
        {
            List<DicCategoryGrid> list = new List<DicCategoryGrid>();
            foreach (DicCategory tempc in iList)
            {
                DicCategoryGrid grid = ConvertToGrid(tempc);
                list.Add(grid);
            }
            return list;
        }

        private void AddDicCategoryRoot()
        {
            IList<DicCategory> list = DicCategoryManager.Find("from DicCategory d where d.Level=0");
            if (list.Count == 0)
            {
                DicCategory root = new DicCategory();
                root.Name = ConfigurationManager.AppSettings["DicRoot"];
                root.Id = Guid.NewGuid().ToString();
                root.ParentId = string.Empty;
                root.TreeCode = "root";
                root.Description = "根节点";
                root.Leaf = false;
                root.Index = 0;
                root.Level = 0;
                DicCategoryManager.Save(root);
            }
        }

        #endregion 
    }
}
